package com.qf.im.ws;

import cn.hutool.json.JSONUtil;
import com.qf.im.entity.Message;
import com.qf.im.utils.ChannelUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MsgInHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("【websocket connecnt】有一个客户端连接了websocket服务器....{}", ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("【websocket connecnt】有一个客户端断开了websocket服务器的连接....", ctx.channel());
        ChannelUtils.remove(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String json = textWebSocketFrame.text();
        log.debug("【websocket get msg】接收到客户端的消息...{}", json);

        //消息转换成实体类
        Message message = JSONUtil.toBean(json, Message.class);

        switch (message.getAction()) {
            case 100 -> {
                //注册消息
                ChannelUtils.put(message.getFrom(), ctx.channel());
            }
            case 101 -> {
                //私聊消息
                Channel channel = ChannelUtils.get(message.getTo());
                //如果对方不在线，则直接不处理
                if (channel == null) return;
                channel.writeAndFlush(new TextWebSocketFrame(json));
            }
        }
    }
}
